/**
 * AI智能助手控制器 - 处理AI聊天和文档分析请求
 *
 * 开发人员：徐少洋
 * 开发时间：2025-10-28 至 2025-11-02
 * 模块职责：提供AI聊天、文档上传解析、流式对话等AI相关功能接口
 *
 * 技术要点：
 * - 多模态AI集成，支持文本、图像、文档等多种输入
 * - SSE流式响应，实现实时对话体验
 * - 文档解析服务，支持PDF、Word等多种格式
 * - Function Calling机制，AI工具调用集成
 * - 多租户数据隔离，确保企业数据安全
 *
 * 开发故事：负责AI功能的控制器开发，与前端AI聊天页面深度集成，实现智能财务分析助手功能，为企业提供专业的财务咨询服务。
 */
package com.pbl.controller;

import com.pbl.ai.AiChatService;
import com.pbl.ai.DocumentParseService;
import com.pbl.common.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/enterprises/{enterpriseId}/ai")
public class AiChatController {

    @Autowired
    private AiChatService aiChatService;

    // @Autowired
    // private DocumentParseService documentParseService;

    @PostMapping("/chat")
    public ApiResponse<AiChatService.ChatResponse> chat(
            @PathVariable Long enterpriseId,
            @RequestBody ChatRequest request) {
        try {
            AiChatService.ChatResponse response = aiChatService.chat(enterpriseId, request.getMessages());
            if (response != null) {
                return ApiResponse.success(response);
            } else {
                return ApiResponse.error(500, "AI服务暂时不可用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500, "聊天失败: " + e.getMessage());
        }
    }

    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatStream(
            @PathVariable Long enterpriseId,
            @RequestBody ChatRequest request) {
        System.out.println("=== AI Chat Stream Request ===");
        System.out.println("Enterprise ID: " + enterpriseId);
        System.out.println("Messages count: " + (request.getMessages() != null ? request.getMessages().size() : 0));
        
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时
        
        try {
            // 异步处理流式响应
            System.out.println("Starting stream response...");
            aiChatService.chatStream(enterpriseId, request.getMessages(), emitter);
        } catch (Exception e) {
            System.err.println("Stream error: " + e.getMessage());
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("{\"error\":\"" + e.getMessage() + "\"}"));
                emitter.complete();
            } catch (IOException ioException) {
                emitter.completeWithError(ioException);
            }
        }
        
        return emitter;
    }

    @PostMapping("/upload")
    public ApiResponse<UploadResponse> uploadFile(
            @PathVariable Long enterpriseId,
            @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.error(400, "文件不能为空");
            }

            // 暂时禁用文件解析功能
            return ApiResponse.error(400, "文件上传功能暂时不可用");
            
            // if (!documentParseService.isSupportedFileType(file.getOriginalFilename())) {
            //     return ApiResponse.error(400, "不支持的文件类型，请上传PDF、DOC、DOCX或TXT文件");
            // }

            // String content = documentParseService.parseDocument(file);
            
            // UploadResponse response = new UploadResponse();
            // response.setFileName(file.getOriginalFilename());
            // response.setFileSize(file.getSize());
            // response.setContent(content);
            // response.setContentLength(content.length());
            
            // return ApiResponse.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500, "文件解析失败: " + e.getMessage());
        }
    }

    @PostMapping("/analyze-image")
    public ApiResponse<AiChatService.ChatResponse> analyzeImage(
            @PathVariable Long enterpriseId,
            @RequestBody ImageAnalysisRequest request) {
        try {
            List<AiChatService.ChatMessage> messages = new ArrayList<>();
            
            // 构建包含图片的消息
            AiChatService.ChatMessage message = new AiChatService.ChatMessage();
            message.setRole("user");
            message.setContent(request.getPrompt() + "\n\n[图片URL: " + request.getImageUrl() + "]");
            messages.add(message);
            
            AiChatService.ChatResponse response = aiChatService.chat(enterpriseId, messages);
            if (response != null) {
                return ApiResponse.success(response);
            } else {
                return ApiResponse.error(500, "图片分析失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500, "图片分析失败: " + e.getMessage());
        }
    }

    // 请求和响应类
    public static class ChatRequest {
        private List<AiChatService.ChatMessage> messages;

        public List<AiChatService.ChatMessage> getMessages() {
            return messages;
        }

        public void setMessages(List<AiChatService.ChatMessage> messages) {
            this.messages = messages;
        }
    }

    public static class ImageAnalysisRequest {
        private String imageUrl;
        private String prompt;

        public String getImageUrl() {
            return imageUrl;
        }

        public void setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
        }

        public String getPrompt() {
            return prompt;
        }

        public void setPrompt(String prompt) {
            this.prompt = prompt;
        }
    }

    public static class UploadResponse {
        private String fileName;
        private long fileSize;
        private String content;
        private int contentLength;

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public long getFileSize() {
            return fileSize;
        }

        public void setFileSize(long fileSize) {
            this.fileSize = fileSize;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public int getContentLength() {
            return contentLength;
        }

        public void setContentLength(int contentLength) {
            this.contentLength = contentLength;
        }
    }
}
